// 获取用户信息，客户端主动发起
var appUserId = null,
  appClientLable = null;
function getparameter(str){
  appUserId = str.split(',')[0];
  appClientLable = str.split(',')[1];
}
// toast
var toast = {
  show: function(msg, delaytime){
      if(this.visible()){
          toast.hide();
      }
      var tpl = '<div class="toast"><p>' + this._msg(msg) + '</p></div>';
      $("body").append(tpl);
      if(delaytime){
          var t= setTimeout(function(){
              toast.hide();
          }, delaytime);
      }
  },
  success: function(msg, delaytime){
      var tpl = '<p><span class="toast-icon toast-success"></span>' + this._msg(msg)+'</p>';
      this.show(tpl,delaytime);
  },
  info: function(msg, delaytime){
      var tpl = '<span class="toast-icon toast-info"></span>' + this._msg(msg);
      this.show(tpl,delaytime);
  },
  error: function(msg, delaytime){
      var tpl = '<span class="toast-icon toast-error"></span>' + this._msg(msg);
      this.show(tpl,delaytime);
  },
  loading: function(msg){
    var tpl = '<div class="toast-icon">\
        <span class="toast-loading-leaf toast-loading-leaf-0"></span>\
        <span class="toast-loading-leaf toast-loading-leaf-1"></span>\
        <span class="toast-loading-leaf toast-loading-leaf-2"></span>\
        <span class="toast-loading-leaf toast-loading-leaf-3"></span>\
        <span class="toast-loading-leaf toast-loading-leaf-4"></span>\
        <span class="toast-loading-leaf toast-loading-leaf-5"></span>\
        <span class="toast-loading-leaf toast-loading-leaf-6"></span>\
        <span class="toast-loading-leaf toast-loading-leaf-7"></span>\
    </div>'+this._msg(msg);
    this.show(tpl);
  },
  hide: function(){
      $(".toast").remove();
  },
  visible: function(){
      return Boolean($(".toast").length);
  },
  _msg: function(msg){
      return msg || "";
  }
}

// 新页打开内容外链
function openVoteDetail(url){
  location.href = url;
}
function openNewWindow(url){
  var userAgent = window.navigator.userAgent.toLocaleLowerCase();
  if (userAgent.indexOf('iphone') > -1 || userAgent.indexOf('ipad') > -1 || userAgent.indexOf('ipod') > -1) {
    var start = userAgent.indexOf('os '),
      versions = + userAgent.substr(start + 3, 3).replace( '_', '.' );
    if (versions >= 8) {
      // window.webkit.messageHandlers.nativeOpenNewWindow.postMessage(url);
      window.webkit.messageHandlers.nativeOpenRelatedNews.postMessage({
        'linkurl': url,
        'opentype': 5004,
        'newstype': 1004
      });
    } else {
      // nativeOpenRelatedNews();
      nativeOpenNewWindow();
    }
  } else {
    // window.jsInterface.nativeOpenNewWindow(url);
    window.jsInterface.nativeOpenRelatedNews({
      'linkurl': url,
      'opentype': 5004,
      'newstype': 1004
    });
  }
}

// 发起APP登录
function toLogin(){
  var userAgent = window.navigator.userAgent.toLocaleLowerCase();
  if (userAgent.indexOf('iphone') > -1 || userAgent.indexOf('ipad') > -1 || userAgent.indexOf('ipod') > -1) {
    var start = userAgent.indexOf('os '),
      versions = + userAgent.substr(start + 3, 3).replace( '_', '.' );
    if (versions >= 8) {
      window.webkit.messageHandlers.nativeLogin.postMessage(null);
    } else {
      nativeLogin();
    }
  } else {
    window.jsInterface.nativeLogin();
  }
}

  // 视频播放
function playVideo(obj, videoUrl, poster){


  var dpr = window.devicePixelRatio || 2;
  var $this = $(obj);
  var videoData = {
      url: videoUrl,
      poster: poster,
      x: $this.position().left / dpr,
      y: $this.position().top / dpr,
      w: parseInt($this.width() / dpr) ,
      h: parseInt($this.height() /dpr)
  };

  var userAgent = window.navigator.userAgent.toLocaleLowerCase();
  if (userAgent.indexOf('iphone') > -1 || userAgent.indexOf('ipad') > -1 || userAgent.indexOf('ipod') > -1) {
    var start = userAgent.indexOf('os '),
      versions = + userAgent.substr(start + 3, 3).replace( '_', '.' );
    if (versions >= 8) {
       window.webkit.messageHandlers.nativePlayVideo.postMessage(JSON.stringify(videoData));
    } else {
      nativePlayVideo(JSON.stringify(videoData));
    }
  } else {
    window.jsInterface.nativePlayVideo(JSON.stringify(videoData));
  }
}

// 图片预览
function previewImage(imgList){
  var userAgent = window.navigator.userAgent.toLocaleLowerCase();
  if (userAgent.indexOf('iphone') > -1 || userAgent.indexOf('ipad') > -1 || userAgent.indexOf('ipod') > -1) {
    var start = userAgent.indexOf('os '),
      versions = + userAgent.substr(start + 3, 3).replace( '_', '.' );
    if (versions >= 8) {
      window.webkit.messageHandlers.nativePreviewImage.postMessage(imgList);
    } else {
      nativePreviewImage(imgList);
    }
  } else {
    window.jsInterface.nativePreviewImage(imgList);
  }
}

//获取地址参数
function urlParams(){
  var urlParams = {},
    search = window.location.search.substr(1);
  if (search) {
    var params = search.split('&');
    params.forEach(function(item){
      var _item = item.split('=');
      urlParams[_item[0]] = decodeURIComponent(_item[1]);
    });
  }
  urlParams['hash'] = location.hash;
  return urlParams;
}

var voteParams = urlParams();

function voteAjax(url, data, callback){
  $.ajax({
    "type": "POST",
    "dataType": "json",
    "contentType": "application/json",
    "url": url,
    "data": JSON.stringify(data),
    "success": function(res){
      callback(res);
    }
  });
}

// 投票列表
function getVoteList(param,callback){
  voteAjax("/real/v400/active/vote", {"id": voteParams['id'],"userID":param.appUserId,"clientLable":param.appClientLable}, function(res){
    if (res['state'] == 0) {
      callback(res['data']);
    } else {
      alert(res['message']);
    }
  });
}

// 投票排行
function getRankList(callback){
  voteAjax("/real/v400/active/rankList", {"id": voteParams['id']}, function(res){
    if (res['state'] == 0) {
      callback(res['data']);
    } else {
      toast.info(res['message']);
    }
  });
}

// 获取投票项信息
function getVotedetail(callback){
  voteAjax("/real/v400/active/optionDetail", {"id": voteParams['id'], "optionId": voteParams['optionid']}, function(res){
    if (res['state'] == 0) {
      callback(res['data']);
    } else {
      alert(res['message']);
    }
  });
}

// 投票
function submitVote(id, needlogin, callback){
  var userAgent = window.navigator.userAgent.toLocaleLowerCase();
  
  if (userAgent.indexOf('jjrb') > -1) {
    if(needlogin == '1'){//需要登录
      // 已登录
      if (appUserId && appUserId != '0') {
        voteAjax("/real/v400/active/submitVote", {"id": voteParams['id'], "detailIds": [id], "userID": appUserId, "clientLable": appClientLable}, function(res){
          if (res['state'] == 0) {
            callback(res);
          } else {
            toast.success(res['message'],1500);
          }
        });
      } else {
        // 未登录，发起APP登录
        toLogin();
      }
    }else{
      voteAjax("/real/v400/active/submitVote", {"id": voteParams['id'], "detailIds": [id], "userID": appUserId, "clientLable": appClientLable}, function(res){
        if (res['state'] == 0) {
          callback(res);
        } else {
          toast.success(res['message'],1500);
        }
      });
    }
  } else {
    // 打开APP
    openApp();
  }
  
}

// 唤醒客户端
function openApp(){
  var androidUrl = "https://static.jingjiribao.cn/package/jingjiribao_v2.1.0.apk",
    iosUrl = "https://itunes.apple.com/cn/app/xin-hua-she-fa-bu/id1024873168?l=cn&mt=8",
    wxUrl = "http://a.app.qq.com/o/simple.jsp?pkgname=com.tianwen.jjrb",
    linkUrl = "http://d.jingjiribao.cn",
    id = voteParams['newsId'],
    newstype = '1001',
    doctype = 0;

  var userAgent = window.navigator.userAgent.toLocaleLowerCase();
  if (userAgent.indexOf('micromessenger') > -1) {
    var isWx = true;
  } else {
    var isWx = false;
  }
  if (userAgent.indexOf('iphone') > -1 || userAgent.indexOf('ipad') > -1 || userAgent.indexOf('ipod') > -1) {
    var start = userAgent.indexOf('os '),
      versions = + userAgent.substr(start + 3, 3).replace( '_', '.' );

    if (versions >= 9) {
      window.location.href = linkUrl + "?id=" + id + "&newstype=" + newstype + "&doctype=" + doctype;
    } else if (isWx) {
      window.location.href = wxUrl;
    } else {
      window.location.href = linkUrl + "?id=" + id + "&newstype=" + newstype + "&doctype=" + doctype;
      setTimeout(function(){
        window.location.href = iosUrl;
      }, 3000);
    }
  } else {
    if (isWx) {
      window.location.href = wxUrl;
    } else {
      window.location.href = "jjrb://news?id=" + id + "&newstype=1004" ;
      setTimeout(function(){
        window.location.href = linkUrl;
      }, 3000);
    }
  }
}
// 浏览器检测
var browser = {
    versions: function () {
        var u = navigator.userAgent, app = navigator.appVersion;
        return {
            trident: u.indexOf('Trident') > -1, 
            presto: u.indexOf('Presto') > -1,
            webKit: u.indexOf('AppleWebKit') > -1,
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,
            mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/) && u.indexOf('Chrome') == -1,
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
            iPhone: u.indexOf('iPhone') > -1 ,
            iPad: u.indexOf('iPad') > -1,
            webApp: u.indexOf('Safari') == -1,
            weixin: u.indexOf('MicroMessenger') > -1,
            myApp: u.indexOf('jjrb') > -1
        };
    }()
};

// 微信分享
if(browser.versions.weixin){
    $.ajax({
        type: "get",
        url: 'https://open.jingjiribao.cn/wxHandler.ashx?site=jjrb&action=getWeixinConfig&callback=?',
        dataType: 'jsonp',
        jsonp: 'jsoncallback',
        success: function(dataObj){
          wx.config(dataObj);
        }
    });
}

function wxShare(title, desc, imgUrl, link, cancel, success){
  if(browser.versions.weixin){
    if(!link || link.length == 0){
        link = window.location.href;
    }
    wx.ready(function () {
      var shareData = {
        title: title,
        desc: desc,
        link: link,
        imgUrl: imgUrl,
        cancel: function () {
          if(cancel){
            cancel();
          }
        },
        success:function(){
          if(success){
            success();
          }
        }
      };
      wx.onMenuShareAppMessage(shareData);
      wx.onMenuShareQQ(shareData);
      wx.onMenuShareQZone(shareData);
      wx.onMenuShareTimeline(shareData);
    });

    wx.error(function (res) {
      console.log(res.errMsg);
    });
  }
}


